package myClient.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import myClient.session.ClientSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import protobuf.ProtoInstance;
import protobuf.protoClass.ProtoMsg;

@ChannelHandler.Sharable
@Service("LoginResponseHandler")
public class LoginResponseHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private ChatMsgHandler chatMsgHandler;

    @Autowired
    private HeartBeatClientHandler heartBeatClientHandler;

    /**
     * 业务逻辑处理
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断消息实例
        if (!(msg instanceof ProtoMsg.Message protoMsg_Message)) {
            super.channelRead(ctx, msg);
            return;
        }
        //判断类型
        ProtoMsg.HeadType headType = protoMsg_Message.getType();
        if (!headType.equals(ProtoMsg.HeadType.LOGIN_RESPONSE)) {
            super.channelRead(ctx, msg);
            return;
        }
        //判断返回是否成功
        ProtoMsg.LoginResponse loginResponse = protoMsg_Message.getLoginResponse();

        ProtoInstance.LoginResponseStateCodeEnum result =
                ProtoInstance.LoginResponseStateCodeEnum.values()[loginResponse.getCode()];

        if (!result.equals(ProtoInstance.LoginResponseStateCodeEnum.SUCCESS)) {
            //登录失败
            System.out.println(result.getDesc());
        } else {
            //登录成功
            ClientSession.loginSuccess(ctx, protoMsg_Message);
            ChannelPipeline pipeline = ctx.pipeline();
            //移除登录响应处理器
            pipeline.remove(this);
            //在编码器后面，动态插入心跳处理器，聊天信息处理器
            pipeline.addAfter("encoder", "heartbeat", heartBeatClientHandler);
            pipeline.addAfter("encoder", "chat", chatMsgHandler);

            heartBeatClientHandler.channelActive(ctx);
        }

    }

}
